import json

import requests
import re
from urllib3.exceptions import InsecureRequestWarning
import time


def get_min_line_data(code):
    """获取股票的分钟数据"""
    data = {}
    timeout = 5  # timeout修改了超时时间，以秒为单位
    # 构造URL请求、user-agent头文件
    url = 'https://quotes.sina.cn/cn/api/openapi.php/CN_MinlineService.getMinlineData?symbol=' + code + '&callback=var' \
                                                                                                        '%20t1' + code + '=&dpc=1 '
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False, timeout=timeout).text
        _str = re.search('\{\S*\}', html).group()
        html = json.loads(_str)
    except Exception as spider_error:
        raise ValueError(spider_error)
    return html


def get_stock_data(code):
    """获取股票的涨幅等数据"""
    data = {}
    timeout = 5  # timeout修改了超时时间，以秒为单位
    # 构造URL请求、user-agent头文件
    url = 'https://hq.sinajs.cn/etag.php?_=' + str(int(round(time.time()) * 1000)) + '&list=' + code
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.get(url=url, data=data, headers=headers, verify=False, timeout=timeout).text
        _str = re.search('\"\S*\"', html).group()
        html = json.loads(_str)
    except Exception as spider_error:
        raise ValueError(spider_error)
    return html


if __name__ == "__main__":
    print(get_stock_data('sz002432'))
